package com.wuchengdong.web.extend.auth;

import com.wuchengdong.web.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;

import static com.wuchengdong.web.extend.utils.ValidateCodeOrTokenUtils.generateToken;

/**
 * 以redis实现的维护token数据的类
 */
@Component
public class RedisAuthHandler implements AuthHandler {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public String saveNewTokenWithUser(User user) {
        String token = generateToken(32);
        redisTemplate.opsForValue().set(token, String.valueOf(user.getId()));
        return token;
    }

    @Override
    public void cleanTokenWithUser(String token,int id) {
        redisTemplate.delete(token);
    }

    @Override
    public int getUserByToken(String token) {
        return Integer.parseInt(Objects.requireNonNull(redisTemplate.opsForValue().get(token)));
    }

    @Override
    public boolean checkToken(String token, User user) {
        return Objects.equals(redisTemplate.opsForValue().get(token), String.valueOf(user.getId()));
    }
}
